package role

import (
	"errors"
	"fmt"
	"gorm-demo/global"
	"gorm-demo/model"
	"gorm-demo/model/request"
	"gorm-demo/model/response"
	"gorm.io/gorm"
	"strconv"
	"sync"
)

func GetRoles() []response.RoleList {
	var roles []model.Role
	global.DB.Find(&roles)
	var rst []response.RoleList
	for _, role := range roles {
		rst = append(rst, response.RoleList{
			ID:   int(role.ID),
			Name: role.Name,
		})
	}
	return rst
}

func AddRole(roles request.RoleRequest) {
	var r []model.Role
	for _, role := range roles.Roles {
		r = append(r, model.Role{Name: role.Name})
	}
	global.DB.CreateInBatches(r, len(roles.Roles))
}

func UpdateRoles(roles request.RoleRequest) error {
	var roleList []model.Role
	for _, i := range roles.Roles {
		id, err := strconv.Atoi(i.Id)
		if i.Id == "" || err != nil {
			return errors.New("参数错误")
		}
		roleList = append(roleList, model.Role{Model: gorm.Model{ID: uint(id)}, Name: i.Name})
	}
	fmt.Println(roleList)
	global.DB.Save(roleList)
	return nil
}

func BatchDeleteRole(ids []string) error {
	DB := global.DB
	wg := sync.WaitGroup{}
	for i := range ids {
		wg.Add(3)
		id, _ := strconv.Atoi(ids[i])
		var role = &model.Role{Model: gorm.Model{ID: uint(id)}}
		go func() {
			DB.Model(role).Association("Users").Clear()
			wg.Done()
		}()
		go func() {
			DB.Model(role).Association("Permissions").Clear()
			wg.Done()
		}()
		go func() {
			DB.Delete(role)
			wg.Done()
		}()
	}
	wg.Wait()
	return nil
}
